<template>
	<view>
		<view class="goods-list">
		  <view
        v-for="(goods, index) in goodsList"
        :key="index"
        @click="gotoDetail(goods)"
      >
        <!-- 组件动态传参 -->
        <my-goods :goods="goods"></my-goods>
      </view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 请求参数对象
        queryObj: {
          // 查询关键词
          query: '',
          // 商品分类id
          cid: '',
          // 页码
          pagenum: 1,
          // 每页条数
          pagesize: 10
        },
        // 商品列表数据
        goodsList: [],
        // 总条数
        total: 0,
        // 是否正在请求数据
        isLoading: false
			}
		},
    onLoad(options) {
      // console.log(options);
      this.queryObj.query = options.query || ''
      this.queryObj.cid = options.cid || ''
      this.getGoodsList()
    },
    methods: {
      // 获取商品列表数据
      async getGoodsList(cb) {
        this.isLoading = true
        const { data: res } = await uni.$http.get('/api/public/v1/goods/search', this.queryObj)
        // 关闭节流阀
        this.isLoading = false
        // 数据请求完毕，调用回调函数
        cb && cb()
        
        if (res.meta.status !== 200) return uni.$showMsg()
        // 给数据赋值
        this.goodsList = [...this.goodsList, ...res.message.goods]
        this.total = res.message.total
      },
      // 点击跳转页面
      gotoDetail(item) {
        uni.navigateTo({
          url: `/subpkg/goods_detail/goods_detail?goods_id=${item.goods_id}`
        })
      }
    },
    // 触底事件监听
    onReachBottom() {
      if (this.goodsList.length >= this.total) return uni.$showMsg('数据加载完毕！')
      if (this.isLoading) return
      // 页码自增
      this.queryObj.pagenum ++
      // 重新获取
      this.getGoodsList()
    },
    // 下拉刷新事件
    onPullDownRefresh() {
      // 1. 重置关键数据
        this.queryObj.pagenum = 1
        this.total = 0
        this.isLoading = false
        this.goodsList = []
      
        // 2. 重新发起请求
        this.getGoodsList(() => uni.stopPullDownRefresh())
    }
	}
</script>

<style lang="scss">

</style>
